package movee.resilience4j;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 *
 * @author movee
 */
@Service
@Slf4j
public class CircuitBreakerExam {

    private final CircuitBreakerRegistry circuitBreakerRegistry;
    private final ExamService examService;

    @Autowired
    public CircuitBreakerExam(CircuitBreakerRegistry circuitBreakerRegistry,
                              ExamService examService) {
        this.circuitBreakerRegistry = circuitBreakerRegistry;
        this.examService = examService;
    }

    /**
     * 通过装饰器装饰被调用方法，实现断路器功能
     * @throws Throwable t
     */
    public void decorateInvoke() throws Throwable {
        CircuitBreaker cb = getCircuitBreakerInstance("backendA");

        for (int i = 0; i < 20; i++) {
            try {
                cb.executeCheckedRunnable(examService::call);
            } catch (IOException e) {
                log.error("catch ioexception");
            }
        }
    }

    /**
     * 通过被调用方法上添加注解，实现断路器功能
     *
     */
    public void aopInvoke() {
        CircuitBreaker cb = getCircuitBreakerInstance("backendA");


        for (int i = 0; i < 20; i++) {
            try {
                log.info("{}:{}:{}", cb.getMetrics().getNumberOfFailedCalls(),
                        cb.getMetrics().getNumberOfSuccessfulCalls(),
                        cb.getMetrics().getNumberOfBufferedCalls());
                log.info("{}", cb.getState());
                examService.call();
            } catch (IOException e) {
                log.error("catch ioexception");
            }
        }
    }

    private CircuitBreaker getCircuitBreakerInstance(String name) {
        CircuitBreaker cb = circuitBreakerRegistry.circuitBreaker(name);

        cb.getEventPublisher()
                .onSuccess(event -> log.info("success"))
                .onError(event -> log.info("error"))
                .onIgnoredError(event -> log.info("ignore"))
                .onReset(event -> log.info("reset"))
                .onStateTransition(event -> log.info("{}", event));

        return cb;
    }

}
